package com.ruoyi.admin.controller;

import com.aliyun.oss.OSS;
import com.ruoyi.admin.common.config.OSSConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

@RestController
@RequestMapping("system/file")
public class FileController {


    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSConfig ossConfig;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PreAuthorize("@ss.checkRole('admin|teacher|student')")
    @PostMapping("upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {

        InputStream inputStream = file.getInputStream();
        //获取实际名称
        String fileName = file.getOriginalFilename();
        //生成随机唯一值，使用uuid，添加到文件名称里面
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid+fileName;
        //按照当前日期，创建文件夹，上传到创建文件夹里面
        String timeUrl = new DateTime().toString("yyyy/MM/dd");
        fileName = timeUrl+"/"+fileName;
        //调用方法实现上传
        ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
        URL presignedUrl = ossClient.generatePresignedUrl(ossConfig.getBucketName(), fileName, DateTime.now().plusYears(50).toDate());
        // 关闭OSSClient。
        // ossClient.shutdown();
        //上传之后文件路径
        // https://lzq01.oss-cn-beijing.aliyuncs.com/01.jpg
        // String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
        //返回
        return AjaxResult.success(presignedUrl.toString());

    }
}
